package com.android.lovely.ui.activity

import android.os.Bundle
import android.text.style.AbsoluteSizeSpan
import androidx.core.graphics.toColorInt
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.core.text.inSpans
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.data.Language
import com.android.lovely.data.getLanguages
import com.android.lovely.databinding.ActivityLanguageBinding
import com.android.lovely.databinding.ItemLanguageBinding
import com.android.lovely.framework.BaseActivity
import com.android.lovely.framework.BaseAdapter
import com.android.lovely.manager.KVStore
import com.android.lovely.ui.widget.AlphabetTouchView
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import com.kotlin.extensions.coroutine.applicationScope
import com.kotlin.extensions.dimen.Dimension.dp
import com.kotlin.extensions.dimen.Dimension.sp
import com.kotlin.extensions.view.ViewExt.addStatusBarMarginTop
import com.kotlin.extensions.view.ViewExt.clickable

/**
 *
 * @author why
 * @date 2025/3/30 17:21
 */
class CustomLanguagePickerActivity : BaseActivity<ActivityLanguageBinding>() {


    private val adapter by lazy { CustomLanguageAdapter() }

    var currentLanguage = KVStore.speakLanguage
        set(value) {
            field = value
        }

    override fun initView(savedInstanceState: Bundle?) {

        mBinding.back.addStatusBarMarginTop()
        mBinding.back.clickable { onBackPressedDispatcher.onBackPressed() }
        adapter.onItemClick = { item, _ ->
            if (item != null) {
                updateLanguage(item)
            }
            adapter.notifyDataSetChanged()
        }
        mBinding.rv.adapter = adapter
        setTargetLanguage()
        mBinding.confirm.clickable {
            KVStore.speakLanguage = currentLanguage
            finish()
        }
        mBinding.atView.setOnLetterSelectedListener(object :
            AlphabetTouchView.OnLetterSelectedListener {
            override fun onLetterSelected(touchY: Float, letter: String?, isTouch: Boolean) {
                mBinding.tvCount.text = letter
                mBinding.tvCount.isVisible = isTouch
                mBinding.tvCount.y = touchY + 85.dp
                if (!isTouch) {
                    if (letter != null) {
                        for (i in 0 until adapter.itemCount) {
                            val title = adapter.getTitleAtPosition(i)
                            if (title.startsWith(letter, ignoreCase = true)) {
                                mBinding.rv.scrollToPosition(i)
                                break
                            }
                        }
                    }
                }
            }
        })
    }

    private fun updateLanguage(item: Language) {
        currentLanguage = item
        setTargetLanguage()
    }

    /**
     * 设置目标语言的显示文本
     */
    private fun setTargetLanguage() {
        lifecycleScope.launchSafety {
            mBinding.target.text = buildSpannedString {
                // 追加当前语言的提示文本
                append(getString(R.string.current_language))
                append("\u0020")
                bold {
                    inSpans(AbsoluteSizeSpan(16.sp)) {
                        color("#6571F0".toColorInt()) {
                            // 追加当前选中语言的名称
                            append(currentLanguage.name)
                        }
                    }
                }
            }
        }
    }

    inner class CustomLanguageAdapter() :
        BaseAdapter<Language, ItemLanguageBinding>() {

        init {
            // 在应用作用域内启动协程，加载语言数据
            applicationScope.launchSafety {
                list.addAll(getLanguages())
                notifyDataSetChanged()
            }.onError {
                // 处理加载数据时的错误
                it.printStackTrace()
            }
        }

        /**
         * 根据位置获取语言的标题
         *
         * @param position 列表中的位置
         * @return 语言的标题
         */
        fun getTitleAtPosition(position: Int): String {
            return if (position in 0 until list.size) {
                list[position].name
            } else {
                ""
            }
        }

        override fun bindViewWithHolderDetails(
            holder: ViewHolder,
            item: Language?,
            binding: ItemLanguageBinding,
            position: Int
        ) {
            val item = list[position]
            holder.binding.text.text = item.name
            holder.binding.text.isSelected =
                item.code.uppercase() == currentLanguage.code.uppercase()
        }
    }
}
